package org.example.config;

import com.bianmaba.spring.security.basic.details.CurrentUserDetails;
import com.bianmaba.spring.security.basic.details.UserDetailsServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    protected UserDetailsServiceImpl userDetailsService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * token filter.
     *
     * @param request     .
     * @param response    .
     * @param filterChain .
     */
    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {

        //检查登录状态
        if (SecurityContextHolder.getContext().getAuthentication() == null || !SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) {
            String token = request.getHeader("token");
            token = !StringUtils.isEmpty(token) ? token : request.getParameter("token");
            if (!StringUtils.isEmpty(token)) {
                if (redisTemplate.hasKey(token)) {
                    //根据token取出用户名，并获取用户信息
                    String username = redisTemplate.opsForValue().get(token).toString();
                    redisTemplate.expire(token, 30, TimeUnit.MINUTES);
                    CurrentUserDetails userDetails = userDetailsService.findUserByUsername(username);
                    if (userDetails != null) {
                        //生成UsernamePasswordAuthenticationToken并设置Security
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                                request));
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                }
            }
        }

        filterChain.doFilter(request, response);

    }
}